package com.dxy.netty.groupchat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @Description netty群聊服务器
 * @Author dangxianyue
 * @Date 2023/1/6 10:37
 */
public class NettyGroupChatServer {

    private final int port;

    public NettyGroupChatServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new NettyGroupChatServer(8089).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() throws InterruptedException {
        // 创建两个线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 服务器启动引导对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 获取pipeline
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加解码处理器 编码器
                            pipeline.addLast("decoder", new StringDecoder());
                            pipeline.addLast("encoder", new StringEncoder());
                            // 添加业务处理handler
                            pipeline.addLast(new NettyGroupChatServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();
            System.out.println("netty服务器启动成功");
            // 监听关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅关闭线程
            bossGroup.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }

    }
}
